import React, { useEffect } from "react";
import { BrowserRouter, Navigate, Route, Routes } from "react-router-dom";
import styles from "./App.module.css";
import {
  HomePage,
  DetailPage,
  SearchPage,
  SignInPage,
  RegisterPage,
  ShoppingCartPage,
  PlaceOrderPage
} from "./pages";
import { useSelector, useDispatch } from "./redux/hooks";
import { getShoppingCart } from "./redux/shoppingCart/slice";

//! react-router-dom 6.x版本的写法 要加Routes 组件参数是element
//! 6版本不需要exact参数 就能实现路由页面之间的替换

// 创建子路由
const PrivateRoute = (p: { children: any }) => {
  const jwt = useSelector((s) => s.user.token);
  // 如果未登录 跳转到登录页面
  return jwt ? p.children : <Navigate to="/signin" />;
};

const App: React.FC = () => {
  // ! 在app加载的时候就要获取到购物车的数据
  const jwt = useSelector((s) => s.user.token);
  const dispatch = useDispatch();

  useEffect(() => {
    dispatch(getShoppingCart(jwt));
  }, []);

  return (
    <div className={styles.App}>
      <BrowserRouter>
        <Routes>
          <Route path="/" element={<HomePage />} />
          <Route path="/signIn" element={<SignInPage />} />
          <Route path="/register" element={<RegisterPage />} />
          <Route path="/detail/:touristRouteId" element={<DetailPage />} />
          {/* 问号代表参数可选 */}
          <Route path="/search/:keywords" element={<SearchPage />}></Route>
          <Route
            path="/shoppingCart"
            element={
              <PrivateRoute>
                <ShoppingCartPage />
              </PrivateRoute>
            }
          />
           <Route
            path="/placeOrder"
            element={
              <PrivateRoute>
                <PlaceOrderPage />
              </PrivateRoute>
            }
          />
          {/* 添加path * 找不到path的时候匹配404 */}
          <Route path="*" element={<h1 style={{ textAlign: "center" }}>404 not found</h1>} />
        </Routes>
      </BrowserRouter>
    </div>
  );
};

export default App;
